package pedongi.mobile.colorfinder;

import java.util.ArrayList;

import pedongi.mobile.colorfinder.knowledgebase.ColorSet;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableRow;
import android.widget.TextView;

public class EditKnowledgeActivity extends Activity {
	public static final String KB_PREF = "ROOM_FINDER_KB";
	public static final String INDEX_LEGEND_PREF = "ROOM_FINDER_INDEX";
	public static final String ANSWER_SET_PREF = "ROOM_FINDER_ANSWER";
	
	private EditText color1, color2, color3, color4;
	private TextView setName;
	
	private ColorSet currentColorSet = null;
	
	private Button saveButton , searchButton , deleteButton , updateButton;
	private EditText searchKey;
	
	private String currentSet = "";
	
	@Override
	public void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);
		setContentView(R.layout.edit_knowledge);
		
		///INIT
		saveButton = (Button) findViewById(R.id.saveButton);
		searchButton = (Button) findViewById(R.id.searchButton);
		deleteButton = (Button) findViewById(R.id.deleteButton);
		updateButton = (Button) findViewById(R.id.updateButton);
		searchKey = (EditText) findViewById(R.id.searchKey);
		
		color1 = (EditText) findViewById(R.id.attr1);
		color2 = (EditText) findViewById(R.id.attr2);
		color3 = (EditText) findViewById(R.id.attr3);
		color4 = (EditText) findViewById(R.id.attr4);
		setName = (TextView) findViewById(R.id.setName);
		
		init();
		setListener();
	}
	
	private void init() {
		updateButton.setVisibility(View.GONE);
		toggleRows(false);
	}
	
	public void setCurrentSet(String value) {
		currentSet = value;
	}
	
	private void toggleRows(boolean show) {
		TableRow row;
		
		if (show) {
			row = (TableRow)findViewById(R.id.row1); row.setVisibility(View.VISIBLE);
			row = (TableRow)findViewById(R.id.row2); row.setVisibility(View.VISIBLE);
			row = (TableRow)findViewById(R.id.row3); row.setVisibility(View.VISIBLE);
			row = (TableRow)findViewById(R.id.row4); row.setVisibility(View.VISIBLE);
			row = (TableRow)findViewById(R.id.row6); row.setVisibility(View.VISIBLE);
		}
		else {
			row = (TableRow)findViewById(R.id.row1); row.setVisibility(View.GONE);
			row = (TableRow)findViewById(R.id.row2); row.setVisibility(View.GONE);
			row = (TableRow)findViewById(R.id.row3); row.setVisibility(View.GONE);
			row = (TableRow)findViewById(R.id.row4); row.setVisibility(View.GONE);
			row = (TableRow)findViewById(R.id.row5); row.setVisibility(View.GONE);
			row = (TableRow)findViewById(R.id.row6); row.setVisibility(View.GONE);
		}
	}
	
	private void initializeEditor(String key , ColorSet colorSet) {
		currentSet = key;
		toggleRows(true);
		setName.setText("Set #" + key);
		currentColorSet = colorSet;
		if (colorSet != null) {
			deleteButton.setVisibility(View.VISIBLE);
			updateButton.setVisibility(View.VISIBLE);
			ArrayList<String> colors = colorSet.getColors();
			color1.setText(colors.get(0));
			color2.setText(colors.get(1));
			color3.setText(colors.get(2));
			color4.setText(colors.get(3));
		}
		else {
			deleteButton.setVisibility(View.GONE);
			updateButton.setVisibility(View.VISIBLE);
			color1.setText("");
			color2.setText("");
			color3.setText("");
			color4.setText("");
		}
	}
	
	private ProgressDialog dialog;
	private ProgressThread progressThread;
	
	// Define the Handler that receives messages from the thread and update the progress
    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            int total = msg.arg1;
            dialog.setProgress(total);
            if (total >= 100){
                //dismissDialog(PROGRESS_DIALOG);
            	dialog.dismiss();
                progressThread.setState(ProgressThread.STATE_DONE);
                color1.setText("blue");
                color2.setText("green");
                color3.setText("romantic green");
                color4.setText("soft pink");
            }
        }
    };

    /** Nested class that performs progress calculations (counting) */
    private class ProgressThread extends Thread {
        Handler mHandler;
        final static int STATE_DONE = 0;
        final static int STATE_RUNNING = 1;
        int mState;
        int total;
       
        ProgressThread(Handler h) {
            mHandler = h;
        }
       
        public void run() {
            mState = STATE_RUNNING;   
            total = 0;
            while (mState == STATE_RUNNING) {
                try {
                    Thread.sleep(30);
                } catch (InterruptedException e) {
                    Log.e("ERROR", "Thread Interrupted");
                }
                Message msg = mHandler.obtainMessage();
                msg.arg1 = total;
                mHandler.sendMessage(msg);
                total++;
            }
        }
        
        /* sets the current state for the thread,
         * used to stop the thread */
        public void setState(int state) {
            mState = state;
        }
    }
	
	protected Dialog onCreateDialog(int id) {
		dialog = new ProgressDialog(this);
		dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		dialog.setMessage("Updating");
		return dialog;
    }
	
	@Override
    protected void onPrepareDialog(int id, Dialog d) {
        dialog.setProgress(0);
        progressThread = new ProgressThread(handler);
        progressThread.start();
    }
	
	private void setListener() {
		updateButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showDialog(0);
			}
		});
		
		saveButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (!currentSet.equals("")) {
					SharedPreferences answerSet = getSharedPreferences(ANSWER_SET_PREF, 0);
					
					ColorSet set = new ColorSet(currentSet , color1.getText().toString() , color2.getText().toString() , color3.getText().toString() , color4.getText().toString());
					set.save(answerSet);
					
					AlertDialog.Builder builder = new AlertDialog.Builder(EditKnowledgeActivity.this);
					builder.setMessage("Color set #" + currentSet + " saved")
				       	.setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
					AlertDialog alert = builder.create();
					alert.show();
					deleteButton.setVisibility(View.VISIBLE);
					currentColorSet = set;
				}
			}
		});
		
		deleteButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				currentColorSet.delete(getSharedPreferences(ANSWER_SET_PREF, 0));
				finish();
			}
		});
		
		searchButton.setOnClickListener(new View.OnClickListener() {
			
			private boolean procceed = false;
			private void setProceed(boolean value) {
				procceed = value;
			}
			
			@Override
			public void onClick(View v) {
				final String key = searchKey.getText().toString();
				
				SharedPreferences answerSet = getSharedPreferences(ANSWER_SET_PREF, 0);
				String value = answerSet.getString(key, "UNDEFINED");
				
				if (!value.equals("UNDEFINED")) {
					//currentColorSet = ;
					initializeEditor(key, ColorSet.createFromString(currentSet, value));
				}
				else {
					AlertDialog.Builder builder = new AlertDialog.Builder(EditKnowledgeActivity.this);
					builder.setMessage("Color set #" + key + " not found. Do you want to create?")
				       	.setCancelable(false).setPositiveButton("Yes", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								setProceed(true);
								dialog.dismiss();
							}
				       	}).setNegativeButton("No", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								setProceed(false);
								dialog.dismiss();
							}
				       	});
					
					AlertDialog alert = builder.create();
					alert.setOnDismissListener(new DialogInterface.OnDismissListener() {
						@Override
						public void onDismiss(DialogInterface dialog) {
							if (procceed) {
								initializeEditor(key, null);
							}
						}
					});
					alert.show();	
				}
			}
		});
	}
}
